package cn.hloger.spider.demo.chatgptDemo.service;

import cn.hloger.spider.common.bean.IdValueVo;
import cn.hloger.spider.common.cache.ChatCache;
import cn.hloger.spider.demo.chatgptDemo.bean.req.ChatApiReq;
import cn.hloger.spider.demo.chatgptDemo.bean.req.ChatMvcReq;
import cn.hloger.spider.demo.chatgptDemo.bean.req.ChatReq;
import cn.hloger.spider.demo.chatgptDemo.bean.req.ChatResp;
import cn.hloger.spider.demo.chatgptDemo.bean.resp.ChatApiResp;
import cn.hloger.spider.demo.chatgptDemo.enums.RoleEnum;
import cn.hloger.spider.demo.chatgptDemo.messageConverter.MyHttpMessageConverter;
import cn.hloger.spider.demo.newsDemo.enums.LineEnum;
import cn.hloger.spider.utils.ChatUtils;
import cn.hloger.spider.utils.IncreMentUtils;
import cn.hloger.spider.utils.PatternUtils;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * TODO
 *
 * @author huanglong
 * @Description TODO
 * @data 2022/9/12
 */
@Service
public class ChatgptService {


    //    public String BASE_CHAT_URL = "http://139.159.238.3:3002/chat-process";
//    public String BASE_CHAT_URL = "https://ai.cowcow.live/api/chat-process";
    @Value("${base.chat.url:null}")
    public String BASE_CHAT_URL;


    public final static RestTemplate restTemplate = new RestTemplate();

    static {
        restTemplate.getMessageConverters().add(new MyHttpMessageConverter());
    }

    public ChatResp getMessage(ChatMvcReq req) {
        if (StringUtils.isBlank(BASE_CHAT_URL)) {
            throw new IllegalArgumentException("chat网站没有设置");
        }
        ChatReq chatReq = convertReq(req);
//        restTemplate.getMessageConverters().add(new MyHttpMessageConverter());
        try {
            List<ChatResp> resultList = Lists.newArrayList();
            Resource resource = restTemplate.postForObject(BASE_CHAT_URL, chatReq, Resource.class);
            if (resource != null) {
                InputStream inputStream = resource.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    resultList.add(JSONObject.parseObject(line, ChatResp.class));
                }
            }
            return CollectionUtil.getLast(resultList);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static ChatReq convertReq(ChatMvcReq req) {
        ChatReq chatReq = new ChatReq();
        String prompt = req.getPrompt();
        String parentMessageId = req.getParentMessageId();
        Integer roleId = req.getRoleId();
        String role = req.getRole();
        chatReq.setPrompt(prompt);
        if (roleId != null) {
            chatReq.setSystemMessage(RoleEnum.ofCode(roleId).getDesc());
        } else if (StringUtils.isNotBlank(role)) {
            chatReq.setSystemMessage(role);
        } else {
            chatReq.setSystemMessage(RoleEnum.MEIMO.getDesc());
        }
        //上下文
        if (StringUtils.isNotBlank(parentMessageId)) {
            chatReq.getOptions().setParentMessageId(parentMessageId);
        }
        return chatReq;
    }

    /**
     * 直接获得结果,不管上下文
     */
    public String getMessageResult(ChatMvcReq req) {
        ChatResp message = getMessage(req);
        return message.getText();
    }

    public String getSimpleMessage(String message) {
        ChatMvcReq chatMvcReq = new ChatMvcReq();
        chatMvcReq.setPrompt(message);
        return getMessage(chatMvcReq).getText();
    }

    /**
     * 这个是给微信秘书的接口
     *
     * @author huanglong
     * @date 2024/8/1
     * @version 1.0
     */
    public ChatApiResp wechat(ChatApiReq req) {
        ChatMvcReq chatMvcReq = new ChatMvcReq();
        //这里是去掉识别
        IdValueVo idValueVo = PatternUtils.getByContent(req.getWord());
        if (null == idValueVo) {
            ChatUtils.renderChatResp("抱歉,我没有正确的收到你的消息");
        }
        Integer id = idValueVo.getId();
        String parentMessageId = "";
        if (id != null) {
            parentMessageId = chatCache.get(id);
        }
        chatMvcReq.setPrompt(idValueVo.getContent());
        chatMvcReq.setParentMessageId(parentMessageId);
        ChatResp chatResp = getMessage(chatMvcReq);
        if (null == chatResp) {
            return ChatUtils.renderChatResp("抱歉,我不知道如何回答您的问题");
        }
        //计数器,放缓存
        int key = IncreMentUtils.next();
        //放入缓存
        chatCache.putByMaxCount(key, chatResp.getId());
        String text = LineEnum.getChatXmlForCode(chatResp.getText(), key);
        return ChatUtils.renderChatResp(text);
    }

    @Autowired
    ChatCache chatCache;

    public String cache(String message) {
        chatCache.put("1", "233333");
        String s = chatCache.get("1");
        System.out.println(s);
        return s;
    }
}
